﻿using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using com.IronOne.BoardPACWinApp.Common;
using com.IronOne.BoardPACWinApp.View.Page;

namespace com.IronOne.BoardPACWinApp.Helpers
{
    public class NavigationService : INavigationService
    {
        internal Frame RootFrame;

        public NavigationService()
        {
            RootFrame = new Frame();
        }
        
        public void GoBack(Frame frame)
        {
            if (frame == null) return;
            try
            {
                if (frame.CanGoBack && frame.BackStackDepth > 1)
                {
                    while (frame.SourcePageType == typeof (LoginPage))
                    {
                        if (frame.CanGoBack) frame.GoBack();
                    }
                }
                else
                {
                    var pageType = typeof (MeetingsPage);
                    var page = (LayoutAwarePage) frame.Content;
                    if (page != null) page.Frame.Navigate(pageType);
                }
            }
            catch (Exception)
            {
                var pageType = typeof (MeetingsPage);
                var page = (LayoutAwarePage) frame.Content;
                if (page != null) page.Frame.Navigate(pageType);
            }
        }

        public void GoForward()
        {
            RootFrame.GoForward();
        }

        public void NavigateTo(Type pageType)
        {
            var frame = (Frame) Window.Current.Content;
            var page = (LayoutAwarePage) frame.Content;

            if (page != null) page.Frame.Navigate(pageType);
        }

        public void NavigateTo(Type pageType, object parameters)
        {
            var frame = (Frame) Window.Current.Content;
            var page = (LayoutAwarePage) frame.Content;

            if (page != null) page.Frame.Navigate(pageType, parameters);
        }
    }
}